import { ref, onMounted, onUnmounted } from 'vue'
import { fabric } from 'fabric'

export function useCanvas(options = {}) {
  const canvas = ref(null)
  const canvasContainer = ref(null)
  let fabricCanvas = null

  const initCanvas = () => {
    fabricCanvas = new fabric.Canvas(canvas.value, {
      width: options.width || 800,
      height: options.height || 600,
      backgroundColor: options.backgroundColor || '#ffffff',
      ...options
    })

    // 自适应窗口大小
    const handleResize = () => {
      const container = canvasContainer.value
      if (!container) return
      
      const ratio = fabricCanvas.width / fabricCanvas.height
      const containerWidth = container.clientWidth
      const containerHeight = container.clientHeight
      const scale = Math.min(containerWidth / fabricCanvas.width, containerHeight / fabricCanvas.height)
      
      fabricCanvas.setZoom(scale)
      fabricCanvas.setDimensions({
        width: fabricCanvas.width * scale,
        height: fabricCanvas.height * scale
      })
    }

    window.addEventListener('resize', handleResize)
    handleResize()

    onUnmounted(() => {
      window.removeEventListener('resize', handleResize)
      fabricCanvas.dispose()
    })
  }

  const getCanvas = () => fabricCanvas

  return {
    canvas,
    canvasContainer,
    initCanvas,
    getCanvas
  }
} 